package com.ygqh.baby.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;

public class FileUtil {
	
	/**
	 * 获取文件contentType
	 * @param filename
	 * @return
	 */
	public static String getFileContentType(String filename) {
		if (filename!=null && filename.endsWith("pdf")) {
			return "application/pdf";
		}
		Path path = Paths.get(filename);
		String contentType = "";
		try {
			contentType = Files.probeContentType(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return contentType;
	}
	
	/**
	 * 文件下载
	 * @param url
	 * @param filename
	 * @return
	 */
	public static File downloadFileByUrl(String uploadUrl, String directPath, String fileName){
		File file = null;
		try {
			InputStream is = null;
			URL Url = new URL(uploadUrl);
			HttpURLConnection conn = (HttpURLConnection)Url.openConnection();
			conn.setConnectTimeout(3*1000);
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			String contentType = conn.getContentType();
			int index = contentType.indexOf(";");
			if (index != -1) {
				contentType = contentType.substring(0, index);
			}
			if (StringUtils.isBlank(fileName)) {
				fileName = UUID.randomUUID().toString() + ".jpg";
			}
			is = conn.getInputStream();
			if (is==null) {
				return null;
			}
			BufferedInputStream bis = new BufferedInputStream(is);
			file = new File(directPath + "/" + fileName);
			
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(file);
			BufferedOutputStream bos = new BufferedOutputStream(fos);
			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len = bis.read(bytes))!=-1) {
				bos.write(bytes, 0, len);
				bos.flush();
			}
			bos.close();
			fos.close();
			bis.close();
			is.close();
		} catch (Exception e) {
		}
		return file;
	}
	
	/**
	 * 
	 * @Title: getFileInputStreamByUrl
	 * @Description: 获取文件数据流
	 * @param @param url
	 * @param @return    
	 * @return InputStream    
	 * @throws
	 */
	public static InputStream getFileInputStreamByUrl(String url){
		InputStream is = null;
		try {
			URL Url = new URL(url);
			HttpURLConnection conn = (HttpURLConnection)Url.openConnection();
			conn.setConnectTimeout(3*1000);
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			is = conn.getInputStream();
		} catch (Exception e) {
		}
		return is;
	}
	
}
